package com.xl.bigdata.util;

import com.alibaba.fastjson.JSONObject;
import com.xl.bigdata.bean.LxApiLogBean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * @ClassName FastJsonUtil
 * @Description TODO
 * @Author xl.gao
 * @Date 2022/1/10 15:56
 * @Version
 */
public class FastJsonUtil {

    public static synchronized LxApiLogBean getLxSaasLogBean(String json) {


        LxApiLogBean bean = new LxApiLogBean();
        try{

            if (json.contains("SlowGetCustomerBrief") || json.contains("SlowgetWoInfoList")) {
                String messageJson = JSONObject.parseObject(json).getString("message");

                if(messageJson.contains("*|*")){
                    String[] strings = messageJson.split("\\*\\|\\*");

                    if(strings != null && strings.length > 2){
                        String methonName = strings[0];
                        bean.setRequestMethod(methonName);
                        bean.setInterfaceName(methonName);
                        String reqTime = strings[1];
                        bean.setRequestTime(new Integer(reqTime));

                    }
                }

            }
        } catch (Exception e){
//            System.out.println("FastJsonUtil.getLxApiLogBean解析异常："+json) ;
        }


        return bean;
    }

    public static synchronized LxApiLogBean getLxApiLogBean(String json) {


        LxApiLogBean bean = new LxApiLogBean();
        try{

            if (json.contains("message")) {
                String messageJson = JSONObject.parseObject(json).getString("message");
                String timestamp = JSONObject.parseObject(messageJson).getString("time");
                try {
                    SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss Z", Locale.UK);
                    java.util.Date d = format.parse(timestamp);
                    SimpleDateFormat f1 = new SimpleDateFormat("yyyyMMddHHmmss");
                    bean.setRequestDate(f1.format(d));
                    SimpleDateFormat f2 = new SimpleDateFormat("yyyyMMdd");
                    bean.setDatePartition(Integer.parseInt(f2.format(d)));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                String fieldsJson = JSONObject.parseObject(messageJson).getString("fs");
                JSONObject fsJsonObject =  JSONObject.parseObject(fieldsJson);

                // 访问接口的服务器
                String remote_addr = fsJsonObject.getString("re_ad");
                bean.setRemoteAddr(remote_addr);

                // req
                String request = fsJsonObject.getString("req");
                if(request != null){
                    String[] reqStr = request.split(" ");
                    String interfaceName = "";
                    if(reqStr != null && reqStr.length == 3){

                        String interfaceNames = reqStr[1];

                        if(interfaceNames.contains("?")){
                            String[] params = interfaceNames.split("\\?");
                            if(params != null && params.length > 0){
                                interfaceName =params[0];
                            }
                        } else {


                            interfaceName = reqStr[1];
                        }

                        if(interfaceNames.contains("?") && interfaceNames.contains("phone=")){
                            String[] params = interfaceNames.split("\\?");
                            if(params != null && params.length == 2){

                                String[] reals = params[1].split("=");
                                bean.setParam(reals[1]);
                            }

                        }
                        bean.setRequestMethod(reqStr[0]);
                        bean.setInterfaceName(interfaceName);
                    }

                    bean.setRemarks(request);
                }




                // 访问接口的状态
                String status = fsJsonObject.getString("sta");
                bean.setStatus(status);

                // 访问接口的返回值大小
                String bodyBytesSent = fsJsonObject.getString("bo");
                bean.setBodyBytesSent(Integer.parseInt(bodyBytesSent));

                // 访问接口的时长
                String requestTime =fsJsonObject.getString("req_t");
                float reF = Float.valueOf(requestTime)*1000;

                // 真实IP
                String upstreamAddr = fsJsonObject.getString("upstream_addr");
                bean.setUpstreamAddr(upstreamAddr);

                // upstream_status upstream状态
                if(fsJsonObject.containsKey("upstream_status")){
                    String upstreamStatus = fsJsonObject.getString("upstream_status");
                    bean.setUpstreamStatus(upstreamStatus);
                }

                // upstream_response_time 请求过程中，upstream响应时间
                if(fsJsonObject.containsKey("upstream_response_time")){
                    String upstreamResponseTime = fsJsonObject.getString("upstream_response_time");
                    bean.setUpstreamResponseTime( upstreamResponseTime);
                }

                bean.setRequestTime((int) reF);

            }
        } catch (Exception e){
            System.out.println("FastJsonUtil.getLxApiLogBean解析异常："+json) ;
        }


        return bean;
    }

    public static void main(String args[]) {



        String jso = "{\"@timestamp\":\"2021-06-07T08:22:18.306Z\",\"@metadata\":{\"beat\":\"filebeat\",\"type\":\"doc\",\"version\":\"6.5.3\",\"topic\":\"saas_log\"},\"host\":{\"name\":\"hicslave4\",\"arc\n" +
                "hitecture\":\"x86_64\",\"os\":{\"platform\":\"centos\",\"version\":\"6.5 (Final)\",\"family\":\"redhat\",\"codename\":\"Final\"},\"containerized\":true},\"offset\":415527097,\"mess" +
                "age\":\"SlowgetWoInfoList*|*1985*|*查询用户表1:HCC2106034LUPSA6*|*4*|*查询用户表2:7117921797540339871*|*1134*|*查询工单表3:[\\\"HCC210320H65ZPK3\\\",\\\"HCC210130DLF9XP5\\\"]*|*226*|*查询服务>\n" +
                "单表4:[\\\"HCC210320H65ZPK3\\\",\n" +
                "\\\"HCC210130DLF9XP5\\\"]*|*161*|*查询lecc工单5:[][HJJD201022KQHW4S][][YT201\n" +
                "11601057143]*|*459*|*2021-06-07 16:22:17\",\"source\":\"/root/lexin/saas/saas-service-impl-0.0.1-SNAPSHOT/logs/stdout.log\",\"input\":{\"type\":\"log\"},\"prospector\"\n" +
                ":{\"type\":\"log\"},\"beat\":{\"hostname\":\"hicslave4\",\"version\":\"6.5.3\",\"name\":\"hicslave4\"}}";

        getLxSaasLogBean(jso);

        String json = "{\"branch_code\":\"DR\",\"branch_name\":\"重庆工贸公司售后\",\"create_time\":20200630091535,\"employeenumber\":\"HR32C205247\",\"enter_time\":20200629152030,\"fingerprint\":\"\",\"fp1\":\"0000000000000000000000000000000000000000000000000000000000000000000001111110000100001111111000010000111111100001000011100110000100000100011001010000000000000101000000000000010101000000001101110001110011111111110111111111111111111111111111111111111111111111\",\"fp2\":\"ooooooooooooooooodbnoabnoabnobhnolhioooioooilojdneaacaaaaaaaaaaa\",\"height\":2000,\"imguuid\":\"prod/01/01/20200630/cf766080fa2245d3add847068ff7cb51.jpg\",\"inserttime\":20200630092030355,\"photo_address\":\"重庆市大足区205省道靠近号子口（离线）\",\"photo_time\":20200629171555,\"photodistance\":878.5772,\"photolatitude\":\"29.629278\",\"photolongitude\":\"105.740589\",\"product_id\":\"RQRSQ\",\"server_close_time\":20200630091248,\"server_info_id\":\"HR320680\",\"server_name\":\"大足区祥能家电销售部\",\"service_type\":\"调试\",\"url\":\"http://hcc.haier.net/network/commons/getFile?fileId=prod/01/01/20200630/cf766080fa2245d3add847068ff7cb51.jpg\",\"vague\":436.6996991604,\"warrant\":\"保内\",\"width\":928,\"wo_order_no\":\"JN20062906982313\"}/01/01/20200630/7c01e68b607046ab8df1f5c6657dfaaf.jpg\",\"inserttime\":20200630092230155,\"photo_address\":\"山西省太原市小店区靠近连山艺红木厂(经度:112.5319,纬度:37.6815)[相册]\",\"photo_time\":20200630091451,\"photodistance\":276810.22,\"photolatitude\":\"37.681497\",\"photolongitude\":\"112.531928\",\"product_id\":\"PBTV\",\"server_close_time\":20200630091501,\"server_info_id\":\"HR050883\",\"server_name\":\"山西海宜盛贸易有限公司\",\"service_type\":\"维修（用户）\",\"url\":\"http://hcc.haier.net/network/commons/getFile?fileId=prod/01/01/20200630/7c01e68b607046ab8df1f5c6657dfaaf.jpg\",\"vague\":761.83512983,\"warrant\":\"保内\",\"width\":369,\"wo_order_no\":\"JJWX20063000001E\"}";
//        getLxApiLogBean(json);
    }
}
